package com.sgb.kjwl.view.widget.self;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by tdd on 2017/12/29.
 */

public class CircleImageView extends ImageView {
    private Paint mPaint;
    private static PorterDuffXfermode SRC_IN = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);

    public CircleImageView(Context context) {
        this(context, null);
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setFilterBitmap(true);
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
    }

    private Bitmap makeCircleBitmap(Bitmap sourceBitmap) {
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, Math.min(getWidth(), getHeight()) / 2, mPaint);
        mPaint.setXfermode(SRC_IN);
        canvas.drawBitmap(sourceBitmap, 0, 0, mPaint);
        mPaint.setXfermode(null);
        return bitmap;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        super.onDraw(new Canvas(bitmap));
        Bitmap finalBitmap = makeCircleBitmap(bitmap);
        canvas.drawBitmap(finalBitmap, 0, 0, null);
        bitmap.recycle();
        finalBitmap.recycle();
    }
}
